package net.tycmc.cty.ctyms.timejob.iems.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.dao.IBaseDAO;
import net.tycmc.bulb.common.dao.ITransactionDAO;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.bulb.dbutil.global.GlobalDBVar;
import net.tycmc.cty.ctyms.timejob.common.EquipVersionCommon;
import net.tycmc.cty.ctyms.timejob.iems.service.DrivingBehaviorService;

/**
 * 驾驶行为统计
 * @author liuhuanhuan
 */
public class DrivingBehaviorDAO {

	IBaseDAO baseDAO;
	private ITransactionDAO tranDAO;

	/**
	 * 驾驶行为列表查询--驾驶行为提示使用
	 * 5分钟内的驾驶行为
	 * @return
	 */
	public List<Map<String, Object>> drivingBehaviorTip(String[] eventIDDef) {
		//从标记表中查找上次统计的ID  jiyongtian 20140612 调整为 通过ID 来获取此次处理的驾驶行为事件
		/*String strSQL = "select top 1 * from DrivingTipRecord order by Dtr_SrcMsgTime desc";
		Map<String,Object> preMap = this.getBaseDAO().execQueryOne(strSQL, new Object[]{});
		String preMsgTime = DateUtil.addMinute(-30);
		if(!preMap.isEmpty()){
			try{
				preMsgTime = MapGetter.getString(preMap, "Dtr_SrcMsgTime");
			}catch(Exception e){
				e.printStackTrace();
				return null;
			}
		}*/
		List<Map<String, Object>> rsList = new ArrayList<Map<String, Object>>();
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("select mer.MsgER_ID,MsgERC_SysE_ID,MsgERC_RunKm,MsgERC_BgnTime,MsgERC_EndTime,MsgER_Vcl_ID,MsgERC_BgnSpeed,MsgERC_EndSpeed,MsgERC_MaxSpeed,MsgERC_AvgSpeed,MsgER_RcvTime,MsgER_MsgTime, " +
				"DATEDIFF(N,MsgERC_BgnTime,MsgERC_EndTime) as continuedTime,DATEDIFF(S,MsgERC_BgnTime,MsgERC_EndTime) as continuedTimeSec,MsgERC_RecordTimes,MsgERC_Lo,MsgERC_La ");
		strBuff.append("from ");
		strBuff.append("CTY_Egn_B.dbo.Msg_Event_Report mer ");
		strBuff.append("left join CTY_Egn_B.dbo.Msg_Event_Report_Content ON MsgERC_MsgER_ID = mer.MsgER_ID ");
//		strBuff.append("where mer.MsgER_RcvTime>? ");
		strBuff.append("where mer.MsgER_ID > "+eventIDDef[0]+"  and mer.MsgER_ID <= "+eventIDDef[1]+" ");
		
		strBuff.append("and ((MsgERC_BgnTime<=MsgERC_EndTime and msgerc_syse_id!=8) OR (msgerc_syse_id=8))");//过滤条件：开始时间<=结束时间
		//2013-04-08 chengshichao 添加，添加原因：CTY临时调整显示逻辑，暂不统计“急刹车事件”（邮件时间：2013-4-7）。
		//jinjiayu20140927增加急刹车提示统计
//		strBuff.append("and MsgERC_SysE_ID!=8 ");
		try {
//			rsList = this.getBaseDAO().execQuery(strBuff.toString(), new Object[] {preMsgTime});
			rsList = this.getBaseDAO().execQuery(strBuff.toString(), new Object[] {});
		} catch (Exception ex) {
			System.out.println("驾驶行为列表查询出现异常...");
		}
		return rsList;
	}

	/**
	 * 驾驶行为列表查询--驾驶行为统计使用
	 * 当天的驾驶行为
	 * @return
	 */
	public List<Map<String, Object>> drivingBehavior(String[] eventIDDef) {
		String statDate = DateUtil.addDay(-1);
		List<Map<String, Object>> rsList = new ArrayList<Map<String, Object>>();
		//支持414协议
		String termSoft = EquipVersionCommon.getSoftVerByAgrType("DBVcl_JPP");
		String sql = "SELECT *,DATEDIFF(N,MsgERC_BgnTime,MsgERC_EndTime) as continuedTime,DATEDIFF(S,MsgERC_BgnTime,MsgERC_EndTime) as continuedTimeSec " +
				"FROM CTY_Egn_B.dbo.Msg_Event_Report JOIN CTY_Egn_B.dbo.Msg_Event_Report_Content ON MsgERC_MsgER_ID = MsgER_ID " +
				/*"where MsgER_MsgTime >= '"+statDate+" 00:00:00' and MsgER_MsgTime<='"+statDate+" 23:59:59' " +*/
				"where exists(select * from V_VehicleInfo where VehicleID=MsgER_Vcl_ID and Tmnl_SoftEdition in ("+termSoft+")) ";
		sql += "and ((MsgERC_BgnTime<=MsgERC_EndTime and msgerc_syse_id!=8) OR (msgerc_syse_id=8)) ";
		//2013-04-08 chengshichao 添加，添加原因：CTY临时调整显示逻辑，暂不统计“急刹车事件”（邮件时间：2013-4-7）。
		//2014-09-27 fujichuan 3.6.8统计急刹车
		//sql += "and MsgERC_SysE_ID!=8 ";
		sql += "AND MsgER_ID > "+eventIDDef[0]+" and MsgER_ID <= "+eventIDDef[1];
		try {
			rsList = this.getBaseDAO().execQuery(sql, new Object[] {});
		} catch (Exception ex) {
			System.out.println("驾驶行为列表查询出现异常...");
		}
		
		return rsList;
	}
	/**
	 * 驾驶行为提示
	 * @return
	 */
	public void drivingBehaviorTipIn(List<String> sqlList,List<Object[]> paramList) {
		if(paramList==null){
			tranDAO.batch(sqlList);
		}else{
			tranDAO.batch(sqlList,paramList);
		}
	}
	
	/**
	 * 原统计逻辑
	 * 编写人员：刘欢欢
	 * 注释时间：2012-12-5
	 * 注释人员：程世朝
	 * 逻辑说明：一台设备定速巡航每天分段统计
	 */
//	public void CalCruise(){//定速循环统计
//		String curDateBeforeN = DateControl.getCurDateBeforeN(3);
//		String strTbl = GetTimQuery.getMsgTimingQueryOfAll(curDateBeforeN, DateControl.getCurDateBeforeN(0));
//		String sql = "declare @MsgT_CruiseState2 int,"
//			+ "@Count int,"
//			+ "@MsgT_MsgTime2 datetime,"
//			+ "@MsgT_CruiseWorkTime2 float, "
//			+ "@MsgT_CruiseKm2 float "
//			//将近3天的数据按照设备号、信息生成时间排序后放到一个临时表中
//			+ "select   IDENTITY(int,1,1) tblId,MsgT_SysTI_ID,MsgT_Vcl_ID,MsgT_MsgTime,MsgT_CruiseWorkTime,MsgT_CruiseKm,MsgT_CruiseState   into   #tempTbl   FROM ("
//			//筛选定速巡航开启和关闭临界的两条记录 0-1 组合是一条定速巡航记录
//			+ "select MsgT_SysTI_ID,MsgT_Vcl_ID,MsgT_MsgTime,MsgT_CruiseWorkTime,MsgT_CruiseKm,MsgT_CruiseState from ( " 
//			+	"	select ROW_NUMBER() over(order by MsgT_Vcl_ID,MsgT_MsgTime) as rows,a.* "
//			+	"	from ( "
//			+	strTbl
//			+	"	) a "
//			+	") t1 where t1.MsgT_CruiseState <> ( "
//			+	"	select MsgT_CruiseState from ( "
//			+	"		select ROW_NUMBER() over(order by MsgT_Vcl_ID,MsgT_MsgTime) as rows,a.* "
//			+	"		from ( "
//			+	strTbl
//			+	"		) a " 
//			+	"	) t2 where t2.rows = t1.rows + 1 "
//			+	")" 
//			+ ") MsgTInfo ORDER BY MsgT_Vcl_ID,MsgT_MsgTime "
//			+ "DECLARE TEST_CURSOR CURSOR "
//			+ "FOR "
//			//循环定速巡航开启关闭按钮是1（表示开启）的记录--由关闭状态到开启状态表示使用了一次定速巡航
//			+ "	SELECT tblId,MsgT_Vcl_ID,MsgT_MsgTime,MsgT_CruiseWorkTime,MsgT_CruiseKm FROM #tempTbl where  MsgT_CruiseState = 1 and MsgT_MsgTime > CONVERT(VARCHAR(10),GETDATE(),120) + ' 00:00:00'"
//			+ "OPEN TEST_CURSOR " 
//			+ "declare @tblId int,"
//			+ "@MsgT_Vcl_ID decimal," 
//			+ "@MsgT_MsgTime  datetime, "
//			+ "@MsgT_CruiseWorkTime float, "
//			+ "@MsgT_CruiseKm float "
//			+ "FETCH FROM TEST_CURSOR INTO @tblId,@MsgT_Vcl_ID,@MsgT_MsgTime,@MsgT_CruiseWorkTime,@MsgT_CruiseKm "
//			+ "	WHILE @@FETCH_STATUS = 0 "	
//			+ "	BEGIN "
//			//查询当前记录下一条并且定速巡航开启关闭按钮是1（表示开启）的记录 同一个设备
//			+ "		SELECT @MsgT_MsgTime2 = MsgT_MsgTime FROM #tempTbl where  MsgT_CruiseState = 0 AND MsgT_Vcl_ID = @MsgT_Vcl_ID AND tblId = @tblId - 1 "			
//			+ "		IF @MsgT_MsgTime2 IS NOT NULL "//如果查询记录不为空
//			+ "			BEGIN "
//			//判断该信息是否录入过数据库	
//			+ "         	SELECT @Count = COUNT(*) FROM DrivingStatistic WHERE Ds_TipType = 9 and Ds_BgnTime = @MsgT_MsgTime2 and Ds_EndTime = @MsgT_MsgTime and Ds_VclId = @MsgT_Vcl_ID"//并且该信息没有录入过数据库 
//			+ "             IF @Count = 0 BEGIN "//将该条定速巡航记录录入到数据库
//			+ "					INSERT  INTO DrivingStatistic(Ds_VclId,Ds_TipType,Ds_BgnTime,Ds_EndTime,Ds_ContinuedRunMin,Ds_ContinuedRunKm) values(@MsgT_Vcl_ID,9,@MsgT_MsgTime2,@MsgT_MsgTime,@MsgT_CruiseKm - @MsgT_CruiseKm2,@MsgT_CruiseWorkTime-@MsgT_CruiseWorkTime2) "
//			+ "             END      "
//			+ "			END "
//			+ "		FETCH FROM TEST_CURSOR INTO @tblId,@MsgT_Vcl_ID,@MsgT_MsgTime,@MsgT_CruiseWorkTime,@MsgT_CruiseKm "
//			+ "	END	"
//			+ "	CLOSE TEST_CURSOR "		
//			+ "	DEALLOCATE TEST_CURSOR "
//			+ "drop   table   #tempTbl; ";
//		baseDAO.execUpdate(sql, new Object[]{});
//	}
	/**
	 * 定速巡航统计逻辑
	 * 编写人员：程世朝
	 * 编写日期：2012-12-5
	 * 逻辑：一台设备定速巡航一天一次性统计
	 * 支持协议：414，对应软件版本号：CUMM3.6
	 */
	public void CalCruise(){
		//支持414协议包含的软件版本号
		
		//软件版本号拆分、拼接
		String termSoftVer = EquipVersionCommon.getSoftVerByAgrType("DBVcl_JPP");
		
		//指定版本号的设备
		List<Map<String,Object>> vclList = null;
		if(StringUtil.isNullOrEmpty(termSoftVer)){
			String statVclSQL = "select * from V_VehicleInfo where UsefulLife>=GETDATE() and Tmnl_SoftEdition in ("+termSoftVer+");";
			vclList = baseDAO.execQuery(statVclSQL, new Object[]{});
		}else{
			return ;
		}
		if(vclList!=null&&vclList.size()>0){
			//源数据表名
			String tableName = DateUtil.addDay(-1).replace("-", "");
			//判断源数据表是否存在
			String tabIsExistSQL = "select count(1) as counts from CTY_Egn_B.dbo.SysObjects Where XType='U' and Name=?";
			Map<String,Object> tabIsExistMap = baseDAO.execQueryOne(tabIsExistSQL, new Object[]{"Msg_Timing_"+tableName});
			if(MapGetter.getString(tabIsExistMap, "counts").equals("1")){
				//统计逻辑：巡航控制开启点与巡航控制关闭点数据汇总
				StringBuffer msgTimingSQL = new StringBuffer();
				msgTimingSQL.append("select tmp.MsgT_Vcl_ID,tmp.MsgT_MsgTimeB,tmp1.MsgT_MsgTimeE,MsgT_CruiseKmE-tmp.MsgT_CruiseKmB CruiseKm,tmp1.MsgT_CruiseWorkTimeE-tmp.MsgT_CruiseWorkTimeB CruiseWorkTime from ");
				msgTimingSQL.append("(select top 1 MsgT_Vcl_ID,MsgT_MsgTime MsgT_MsgTimeB,MsgT_CruiseKm MsgT_CruiseKmB,MsgT_CruiseWorkTime MsgT_CruiseWorkTimeB from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" where MsgT_Vcl_ID=? and MsgT_CruiseKm is not null and MsgT_CruiseKm <> '0' and MsgT_CruiseWorkTime is not null and MsgT_CruiseWorkTime <> '0' order by MsgT_ID asc)tmp ");
				msgTimingSQL.append("left join ");
				msgTimingSQL.append("(select top 1 MsgT_Vcl_ID,MsgT_MsgTime MsgT_MsgTimeE,MsgT_CruiseKm MsgT_CruiseKmE,MsgT_CruiseWorkTime MsgT_CruiseWorkTimeE from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" where MsgT_Vcl_ID=? and MsgT_CruiseKm is not null and MsgT_CruiseKm <> '0' and MsgT_CruiseWorkTime is not null and MsgT_CruiseWorkTime <> '0' order by MsgT_ID desc)tmp1 ");
				msgTimingSQL.append("on tmp.MsgT_Vcl_ID=tmp1.MsgT_Vcl_ID");
				String instDs = "INSERT  INTO DrivingStatistic(Ds_VclId,Ds_TipType,Ds_BgnTime,Ds_EndTime,Ds_ContinuedRunMin,Ds_ContinuedRunKm) values(?,?,?,?,?,?) ";
				for(Map<String,Object> vclMap:vclList){
					Map<String,Object> msgTimingMap = baseDAO.execQueryOne(msgTimingSQL.toString(), new Object[]{MapGetter.getString(vclMap, "VehicleID"),MapGetter.getString(vclMap, "VehicleID")});
					if(!msgTimingMap.isEmpty()){
						baseDAO.execInsert(instDs, new Object[]{MapGetter.getString(msgTimingMap, "MsgT_Vcl_ID"),9,
								MapGetter.getString(msgTimingMap, "MsgT_MsgTimeB"),MapGetter.getString(msgTimingMap, "MsgT_MsgTimeE"),
								DrivingBehaviorService.getFloat(msgTimingMap, "CruiseWorkTime")*60,DrivingBehaviorService.getFloat(msgTimingMap, "CruiseKm")});
					}
				}
			}
		}else{
			return ;
		}
	}
	/**
	 * 原统计逻辑
	 * 编写人员：刘欢欢
	 * 注释时间：2012-12-5
	 * 注释人员：程世朝
	 * 逻辑说明：一台设备怠速统计每天分段统计
	 */
//	public void CalIdle(){//怠速统计
//		String curDateBeforeN = DateControl.getCurDateBeforeN(3);
//		String strTbl = GetTimQuery.getMsgTimingQuery(curDateBeforeN, DateControl.getCurDateBeforeN(0));//获取近3天的日志表数据
//		String sql = "declare @MsgT_tIdleWorkTime_UDS2 float,"
//			+ "@Count int,"
//			+ "@MsgT_MsgTime2 datetime "
//			+ "select   IDENTITY(int,1,1) tblId,MsgT_SysTI_ID,MsgT_Vcl_ID,MsgT_MsgTime,MsgT_tIdleWorkTime_UDS   into   #tempTbl   FROM ("
//			+ strTbl 
//			+ ") MsgTInfo ORDER BY MsgT_Vcl_ID,MsgT_MsgTime "
//			+ "DECLARE TEST_CURSOR CURSOR "
//			+ "FOR "
//			//循环当天所有的关机信息
//			+ "	SELECT tblId,MsgT_Vcl_ID,MsgT_tIdleWorkTime_UDS,MsgT_MsgTime FROM #tempTbl where  MsgT_SysTI_ID = 17 and MsgT_MsgTime > CONVERT(VARCHAR(10),GETDATE(),120) + ' 00:00:00'"
//			+ "OPEN TEST_CURSOR " 
//			+ "declare @tblId int,"
//			+ "@MsgT_Vcl_ID decimal," 
//			+ "@MsgT_tIdleWorkTime_UDS float,"
//			+ "@MsgT_MsgTime  datetime "
//			+ "FETCH FROM TEST_CURSOR INTO @tblId,@MsgT_Vcl_ID,@MsgT_tIdleWorkTime_UDS,@MsgT_MsgTime "
//			+ "	WHILE @@FETCH_STATUS = 0 "	
//			+ "	BEGIN "
//			//获取当前关机信息的上一条记录
//			+ "		SELECT @MsgT_tIdleWorkTime_UDS2 = MsgT_tIdleWorkTime_UDS,@MsgT_MsgTime2 = MsgT_MsgTime FROM #tempTbl where  MsgT_SysTI_ID = 16 AND MsgT_Vcl_ID = @MsgT_Vcl_ID AND tblId = @tblId - 1 "			
//			+ "		IF (@MsgT_tIdleWorkTime_UDS - @MsgT_tIdleWorkTime_UDS2) > 0 "//如果本次开关机怠速时长大于0
//			+ "			BEGIN "
//			+ "         	SELECT @Count = COUNT(*) FROM DrivingStatistic WHERE Ds_TipType = 1 and Ds_BgnTime = @MsgT_MsgTime2 and Ds_EndTime = @MsgT_MsgTime and Ds_VclId = @MsgT_Vcl_ID"//并且该信息没有录入过数据库
//			+ "             IF @Count = 0 BEGIN "//则将该条怠速记录录入到数据库
//			+ "					INSERT  INTO DrivingStatistic(Ds_VclId,Ds_TipType,Ds_BgnTime,Ds_EndTime,Ds_ContinuedRunMin) values(@MsgT_Vcl_ID,1,@MsgT_MsgTime,@MsgT_MsgTime2,DATEDIFF(N,@MsgT_tIdleWorkTime_UDS2,@MsgT_tIdleWorkTime_UDS)) "
//			+ "             END      "
//			+ "			END "
//			+ "		FETCH FROM TEST_CURSOR INTO @tblId,@MsgT_Vcl_ID,@MsgT_tIdleWorkTime_UDS,@MsgT_MsgTime "
//			+ "	END	"
//			+ "	CLOSE TEST_CURSOR "		
//			+ "	DEALLOCATE TEST_CURSOR "
//			+ "drop   table   #tempTbl; ";
//		
//		baseDAO.execUpdate(sql, new Object[]{});
//	}
	
	/**
	 * 怠速统计逻辑
	 * 编写人员：程世朝
	 * 编写日期：2012-12-5
	 * 逻辑：一台设备怠速一天一次性统计
	 * 支持协议：412、414，对应软件版本号：CUMM3.5、CUMM3.6
	 */
	public void CalIdle(){
		//支持414协议包含的软件版本号
		String termSoftVer = EquipVersionCommon.getSoftVerByAgrType("DBVcl_JPP");

		//指定版本号的设备
		List<Map<String,Object>> vclList = null;
		if(StringUtil.isNullOrEmpty(termSoftVer)){
			String statVclSQL = "select * from V_VehicleInfo where UsefulLife>=GETDATE() and Tmnl_SoftEdition in ("+termSoftVer+");";
			vclList = baseDAO.execQuery(statVclSQL, new Object[]{});
		}else{
			return ;
		}
		if(vclList!=null&&vclList.size()>0){
			//源数据表名
			String tableName = DateUtil.addDay(-1).replace("-", "");
			//判断源数据表是否存在
			String tabIsExistSQL = "select count(1) as counts from CTY_Egn_B.dbo.SysObjects Where XType='U' and Name=?";
			Map<String,Object> tabIsExistMap = baseDAO.execQueryOne(tabIsExistSQL, new Object[]{"Msg_Timing_"+tableName});
			if(MapGetter.getString(tabIsExistMap, "counts").equals("1")){
				//统计逻辑：怠速开启点与怠速关闭点数据汇总
				StringBuffer msgTimingSQL = new StringBuffer();
				msgTimingSQL.append("select tmp.MsgT_Vcl_ID,tmp.MsgT_MsgTimeB,tmp1.MsgT_MsgTimeE,MsgT_tIdleWorkTime_UDSE-MsgT_tIdleWorkTime_UDSB tIdleWorkTime from ");
				msgTimingSQL.append("(select top 1 MsgT_Vcl_ID,MsgT_MsgTime MsgT_MsgTimeB,MsgT_tIdleWorkTime_UDS MsgT_tIdleWorkTime_UDSB from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" where MsgT_Vcl_ID=? and MsgT_tIdleWorkTime_UDS is not null and MsgT_tIdleWorkTime_UDS <> '0' order by MsgT_ID asc)tmp ");
				msgTimingSQL.append("left join ");
				msgTimingSQL.append("(select top 1 MsgT_Vcl_ID,MsgT_MsgTime MsgT_MsgTimeE,MsgT_tIdleWorkTime_UDS MsgT_tIdleWorkTime_UDSE from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" where MsgT_Vcl_ID=? and MsgT_tIdleWorkTime_UDS is not null and MsgT_tIdleWorkTime_UDS <> '0' order by MsgT_ID desc)tmp1 ");
				msgTimingSQL.append("on tmp.MsgT_Vcl_ID=tmp1.MsgT_Vcl_ID ");
				String instDs = "INSERT  INTO DrivingStatistic(Ds_VclId,Ds_TipType,Ds_BgnTime,Ds_EndTime,Ds_ContinuedRunMin) values(?,?,?,?,?) ";
				for(Map<String,Object> vclMap:vclList){
					Map<String,Object> msgTimingMap = baseDAO.execQueryOne(msgTimingSQL.toString(), new Object[]{MapGetter.getString(vclMap, "VehicleID"),MapGetter.getString(vclMap, "VehicleID")});
					if(!msgTimingMap.isEmpty()){
						baseDAO.execInsert(instDs, new Object[]{MapGetter.getString(msgTimingMap, "MsgT_Vcl_ID"),1,
								MapGetter.getString(msgTimingMap, "MsgT_MsgTimeB"),MapGetter.getString(msgTimingMap, "MsgT_MsgTimeE"),
								DrivingBehaviorService.getFloat(msgTimingMap, "tIdleWorkTime")*60});
					}
				}
			}
		}else{
			return ;
		}
	}

	public float getRunKm(String bgnTime,String endTime,String vclId,String tableName){
		float runKm = 0;
		try{
			String strSQL = "select top 1 tRunKmSign=case when MsgT_tRunKm is not null then 1 " +
			"when MsgT_tRunKm is null and MsgT_tRunKmExact is not null then 2 else 3 end " +
			"from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" where MsgT_Vcl_ID=? and MsgT_MsgTime>=? and MsgT_MsgTime<=? ";
			Map<String,Object> tRunKmSignMap = baseDAO.execQueryOne(strSQL, new Object[]{vclId,bgnTime,endTime});
			int tRunKmSign = Integer.valueOf(MapGetter.getString(tRunKmSignMap, "tRunKmSign"));
			StringBuffer strBuff = new StringBuffer();
			strBuff.append("select tmp1.tRunKm-tmp.tRunKm runKm from (");
			String tmpStr1 = "";
			String tmpStr2 = "";
			switch (tRunKmSign){
				case 1:
					tmpStr1 = "select top 1 MsgT_Vcl_ID,ISNULL(MsgT_tRunKm,0) tRunKm ";
					tmpStr2 = "and MsgT_tRunKm is not null";
				break;
				case 2:
					tmpStr1 = "select top 1 MsgT_Vcl_ID,ISNULL(MsgT_tRunKmExact,0) tRunKm ";
					tmpStr2 = "and MsgT_tRunKmExact is not null";
				break;
				case 3:
					tmpStr1 = "select top 1 MsgT_Vcl_ID,ISNULL(MsgT_tRunKmECU,0) tRunKm ";
					tmpStr2 = "and MsgT_tRunKmECU is not null";
				break;
			}
			strBuff.append(tmpStr1);
			strBuff.append("from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" ");
			strBuff.append("where MsgT_Vcl_ID=? and MsgT_MsgTime>=? and MsgT_MsgTime<=? "+tmpStr2+" order by MsgT_MsgTime asc");
			strBuff.append(")tmp left join(");
			strBuff.append(tmpStr1);
			strBuff.append("from CTY_Egn_B.dbo.Msg_Timing_"+tableName+" ");
			strBuff.append("where MsgT_Vcl_ID=? and MsgT_MsgTime>=? and MsgT_MsgTime<=? "+tmpStr2+" order by MsgT_MsgTime desc");
			strBuff.append(") tmp1 on tmp.MsgT_Vcl_ID=tmp1.MsgT_Vcl_ID");
			Map<String,Object> retMap = baseDAO.execQueryOne(strBuff.toString(), new Object[]{vclId,bgnTime,endTime,vclId,bgnTime,endTime,});
			if(StringUtil.isNullOrEmpty(MapGetter.getString(retMap, "runKm"))){
				try{
					runKm = Float.parseFloat(MapGetter.getString(retMap, "runKm"));
				}catch(Exception e){
				}
				
			}
		}catch(Exception e){
		}
		return runKm;
	}
	/**
	 * 安装JPP设备的信息
	 * @return
	 */
	public Map<String,Map<String,Object>> getVclMap(){
		String termSoft = EquipVersionCommon.getSoftVerByAgrType("DBVcl_JPP");

		String strSQL = "select VehicleID,VehicleNumber,DBCode from V_VehicleInfo " +
				"where UsefulLife>GETDATE() and Tmnl_SoftEdition in ("+termSoft+");";
		List<Map<String,Object>> list = baseDAO.execQuery(strSQL, new Object[]{});
		Map<String,Map<String,Object>> vclMap = new HashMap<String,Map<String,Object>>();
		for(Map<String,Object> map:list){
			vclMap.put(MapGetter.getString(map, "VehicleID"), map);
		}
		return vclMap;
	}
	
	public IBaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public ITransactionDAO getTranDAO() {
		return tranDAO;
	}

	public void setTranDAO(ITransactionDAO tranDAO) {
		this.tranDAO = tranDAO;
	}
	
	/**
	 * 获取度量名称列表
	 * @return
	 */
	public List<Map<String, Object>> getLocNameList(int k){
		String sql = "select tmp.SysMTML_ID as nameID,tmp.SysMTML_Name as locName "
				+ "from (select SysMTML_ID,SysMTML_Name,SysMTML_Sys_MT_ID from Sys_MeasureType_MultiLan "
				+ "where SysMTML_SysML_ID = '"+k+"') tmp ";
		
		List<Map<String, Object>> list = baseDAO.execQuery(sql, new Object[]{});
		return list;
		
	}
	/**
	 * 获取此次处理的驾驶行为提示ID,
	 * 无值时，{0,0}
	 * @author jiyongtian 20140612
	 */
	public String[] getEventIDDef() {
		String sql = "select * from (select StatR_StatDataID ,1 worktype from StatRecord where StatR_Type = 5 and StatR_OprtType = 1 "
	               + "union all select MAX(MsgER_ID),2 worktype from CTY_Egn_B.dbo.Msg_Event_Report)tmp where 1=1 order by worktype";
		List<Map<String,Object>> list = this.baseDAO.execQuery(sql, new Object[]{});
		String[] reStr = new String[2];
		if(null != list && !list.isEmpty()){
			reStr[0] = MapGetter.getString(list.get(0),"StatR_StatDataID");
			reStr[1] = MapGetter.getString(list.get(1),"StatR_StatDataID");
		}else{
			reStr[0] = String.valueOf(0);
			reStr[1] = String.valueOf(0);
		}
		return reStr;
	}
	/**
	 * 更新已提示的驾驶行为事件标志ID
	 * @author jiyongtian 20140612
	 */
	public boolean updateWorkedEventID(String eventID) {
		String sql = "update StatRecord set StatR_StatDataID = ?,StatR_UpdateTime = GETDATE() where StatR_Type = 5 and StatR_OprtType = 1 " ;
		int i = this.baseDAO.execUpdate(sql, new Object[]{eventID});
		if(i>0){
			return true;
		}else{
			return false;
		}
	}
	/*从提示开关表中获取驾驶行为提示开关为关的设备号集合
	 * 20141016
	 * wangkai
	 * 3.6.6新增
	 * vclpromptswitch:提示开关表
	 * VclPS_isOpen=0：开关状态为关
	 * VclPS_Type=5：提示开关类型为驾驶行为
	 * */
	public List<String> getdrivingPromtPSwitch() {
		List<String> drivingPromSwitch = new ArrayList<String>();

		String sql = "select VclPS_VclID from " +GlobalDBVar.getDBFullName_Conn("VclPromptSwitch","1",null)+
				" where VclPS_isOpen=0 and VclPS_Type=5 ";
		List<Map<String, Object>> list = baseDAO.execQuery(sql, new Object[] {});
		for (Map<String, Object> map : list) {
			drivingPromSwitch.add(MapGetter.getString(map, "VclPS_VclID"));
		}
		return drivingPromSwitch;
	}
//获取本次统计开始id和结束id
	public String[] getEventID(String MaxID) {
		    String sql = "select StatR_StatDataID ,1 worktype from StatRecord where StatR_Type = 7 and StatR_OprtType = 1 ";
		    List list = this.baseDAO.execQuery(sql, new Object[0]);
		    String[] reStr = new String[2];
		    if ((list != null) && (!(list.isEmpty()))) {
		      reStr[0] = MapGetter.getString((Map)list.get(0), "StatR_StatDataID");
		      reStr[1] = (MapGetter.getInt((Map)list.get(0), "StatR_StatDataID") + 10000)+"";
		    }
		    else
		    {
		      reStr[0] = String.valueOf(0);
		      reStr[1] = String.valueOf(0);
		    }
		    if (Integer.parseInt(reStr[0]) >= Integer.parseInt(MaxID)) {
		      reStr[1] = MaxID;
		    }
		    return reStr;
	}
//更新下次统计设备id的开始值
	public boolean updateEventID(String eventID) {
		String sql = "update StatRecord set StatR_StatDataID = ?,StatR_UpdateTime = GETDATE() where StatR_Type = 7 and StatR_OprtType = 1 " ;
		int i = this.baseDAO.execUpdate(sql, new Object[]{eventID});
		if(i>0){
			return true;
		}else{
			return false;
		}
		
	}
	//获取本次统计开始id和结束id
	public String getMaxEventID() {
		String sql = "select MAX(MsgER_ID) maxid from CTY_Egn_B.dbo.Msg_Event_Report ";
		List<Map<String, Object>> list = this.baseDAO.execQuery(sql,
				new Object[] {});
		String reStr = "0";
		if (null != list && !list.isEmpty()) {
			reStr = MapGetter.getString(list.get(0), "maxid");
		}
		return reStr;
	}
}
